import * as THREE from './threejs/build/three.module.js';
import { createStats } from './js/createStats.js';
import { Viewer } from './js/Viewer.js';
import { ModelLoader } from './js/ModelLoader.js';
import { createMsg } from './js/Msg.js';
import { importHtml } from './js/importHtml.js'
import { Ray } from './js/Ray.js';
import { SmallView } from './js/SmallView.js';
import { RaySmall } from './js/RaySmall.js';
import { Fly } from './js/Fly.js';
import { Turn } from './js/Turn.js';
import { createInfoLabel } from './views/infoLabel.js'

let msg = createMsg(); //消息提示工具

const sc = 50; //模型放大倍数

const objects = []; //所有模型对象，拾取和碰撞检测用

const points = []; //小地图上的点位

let dingArr = []; //顶部模型

let turn; //底部工具条控制

let lastClickPoint; //鼠标上次点击模型的位置

//创建场景
let viewer = new Viewer(
    1,
    50000,
    [-205, 3479, 4412],
    [-179, 186, 519]
);

let camera = viewer.camera;
let scene = viewer.scene;
let renderer = viewer.renderer;
let controls = viewer.controls;
let lableRenderer = viewer.labelRenderer;

controls.enableKeys = false;
controls.rotateSpeed = 0.2;
controls.panSpeed = 0.7;
controls.keyPanSpeed = 15;
controls.maxPolarAngle = 2.356;
controls.minPolarAngle = 0.53;
controls.maxDistance = 10000;
controls.update();

//加载小地图
let smallCameraPosition = [-100, 7500, -100]; //小地图相机位置
let viewPoints = {
    name: ["候车", "安检"],
    position: [[638.788449, -170.65745, 310.149692], [305.418965, 90.472115, 484.154042], [-2707.898336, 445.988392, 552.339882]],
    target: [[-374.937977, -30.807686, 341.367943], [-693.017774, -31.807686, 519.716187], [-1922.742977, -31.807686, 142.053509]]
}; //小地图上的点位
let smallView = new SmallView(viewPoints, smallCameraPosition, camera, points);

//飞行
let fly = new Fly(controls, camera);

//加载模型
async function loadModelsAsync() {
    msg.show("模型加载中，请稍等");
    msg.loading("模型加载中，请稍等");

    await importHtml();

    let modelLoader = new ModelLoader(viewer, sc, objects, smallView, dingArr);
    await Promise.all([
        modelLoader.loadModel('./threejs/GLTF/four/jingui/jg_ding.glb'),
        modelLoader.loadModel('./threejs/GLTF/four/jingui/jg_yc.glb'),
        modelLoader.loadModel('./threejs/GLTF/four/jingui/jg_ec.glb')
    ]);

    msg.show("模型加载完成，您可以操作了");
    msg.loadingClose();

    init();

    animationFrame();
}
loadModelsAsync();

//模型加载完成后初始化
async function init() {

    //详细信息标签
    let infoLabel = await createInfoLabel(sc, scene);

    //相机模型点击
    let ray = new Ray(objects, camera, scene, '', result => {
        if (result.length > 0) {
            let obj = result[0];
            //createMsg().show(mesh.name);
            lastClickPoint = obj.point;
            infoLabel.meshName = obj.name;
            infoLabel.clickPoint = { x: Math.round(obj.point.x), y: Math.round(obj.point.y), z: Math.round(obj.point.z) };
            let pos = obj.mesh.geometry.boundingSphere.center;
            infoLabel.meshCenter = { x: Math.round(pos.x * sc), y: Math.round(pos.y * sc), z: Math.round(pos.z * sc) };
            infoLabel.show(1001, obj.point);
        }
    });
    ray.start();

    //小地图点位点击
    let rayForSmall = new RaySmall(smallView, fly, points);
    rayForSmall.start();

    //底部工具条控制
    let defaultView = {
        position: [-205, 3479, 4412],
        target: [-179, 186, 519]
    };
    turn = new Turn(viewPoints, objects, scene, camera, controls, fly, defaultView, dingArr);
    turn.bindDom();
}

//显示坐标系线
let axisHelper = new THREE.AxisHelper(50000);
//scene.add(axisHelper);

//帧率监测与显示
let stats = createStats();

//ctrl+c复制相机视角
$('#threeContainer').on('keydown', function (e) {
    if (e.ctrlKey && e.key == 'c') {
        let position = JSON.stringify([parseFloat((camera.position.x).toFixed(6)), parseFloat((camera.position.y).toFixed(6)), parseFloat((camera.position.z).toFixed(6))]);
        let target = JSON.stringify([parseFloat((controls.target.x).toFixed(6)), parseFloat((controls.target.y).toFixed(6)), parseFloat((controls.target.z).toFixed(6))]);
        let lastClickPointStr = '';
        if (lastClickPoint) {
            lastClickPointStr = JSON.stringify([parseFloat((lastClickPoint.x).toFixed(6)), parseFloat((lastClickPoint.y).toFixed(6)), parseFloat((lastClickPoint.z).toFixed(6))]);
        }

        let txt = "position：" + position + "\r\n\r\ntarget：" + target + "\r\n\r\nlastClickPoint：" + lastClickPointStr;
        createMsg().show('相机视角已复制到剪贴板');
        navigator.clipboard.writeText(txt); //复制到剪贴板
    }
});

//事件循环
function animationFrame() {
    requestAnimationFrame(animationFrame); //事件循环

    renderer.render(scene, viewer.camera); //场景渲染

    lableRenderer.render(scene, viewer.camera); //标签渲染

    stats.update(); //帧率监测与显示

    smallView && smallView.refresh(); //小地图场景渲染

    fly && fly.refresh(); //飞行

    turn && turn.refresh();

}
